import java.util.ArrayList;
import java.util.List;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

final String uriRoot = "http://test1.e-agri.net/";
final String fileRoot = "/home/rota/Pictures";
final String fileName = "profile.jpg";

final Log log = LogFactory.getLog("wap.groovy");

def printMatches(mat){
		Log log = LogFactory.getLog("wap.groovy");
		StringBuffer buf = new StringBuffer();

        if(mat.size() > 0)
             for(int i=0; i<mat.size(); i++){
                	for(int j=1; j<mat[i].size(); j++)
                        buf.append("\t[").append(j).append("] ").append(mat[i][j]);
               
               
               		buf.append("\n");
               }

		log.info(buf.toString());
}

def convertMatchesToJson(mat, fields, getSection, sectionState){
		Log log = LogFactory.getLog("wap.groovy");

		StringBuffer buf = new StringBuffer();
		buf.append("{\"fields\":[");
		int f = 0;

		for(def field : fields){
			if(f>0)
				buf.append(",");

			buf.append("\"").append(field).append("\"");
			f++;
		}
		buf.append("]");

		buf.append(",\"data\":[");
		for(int i=0; i<mat.size(); i++){
			if(i>0)
				buf.append(",");

			buf.append("[");
				buf.append(getSection(mat[i], sectionState));

				for(int j=1; j<mat[i].size(); j++){
					buf.append(",\"");
					
					buf.append(mat[i][j]
						.replace(",", "\\\\,")
						.replace("{", "\\\\{")
						.replace("}", "\\\\}")
						.replace("[", "\\\\[")
						.replace("]", "\\\\]")
					);
					
					buf.append("\"");
				}
			
			buf.append("]");
		}
		buf.append("]}");
 
     return buf.toString();
}

class TopPageSection {

	public int gotDiaryPosts = 0;

	public int gotCommunityPosts = 0;

	public String lastSectionUrl = "";
	
	public Map<Integer, Integer> rowsInSection = new HashMap<Integer, Integer>();

	public String toString(){
		return "{D:" + gotDiaryPosts + ", C:" + gotCommunityPosts + "}";
	}
}

def returnZero(mat, sections){
	return 0;
}

def getTopPageSection(mat, sections){
		Log log = LogFactory.getLog("wap.groovy");
	
	int section = -1;

	if(!sections.lastSectionUrl.equals(mat[2].substring(0, 25))) {

		if(mat[2].indexOf("a=page_c_topic_detail") > -1){
			if (sections.gotCommunityPosts == 0){
				 if(sections.gotDiaryPosts == 0){
					sections.gotDiaryPosts = 1;
				 }else{
					sections.gotCommunityPosts = 1;
				 }
			}
		}
	}
	sections.lastSectionUrl = mat[2].substring(0, 25);

	if(mat[2].indexOf("a=page_fh_album") > -1){
		section = 2;
	}else if(mat[2].indexOf("a=page_fh_diary") > -1){
		if(sections.gotDiaryPosts == 0)
			section = 0;
		else
			section = 3;
	}else if(mat[2].indexOf("a=page_c_topic_detail") > -1){
		if(sections.gotCommunityPosts == 0)
			section = 1;
		else
			section = 4;
	}
	
	if(!sections.rowsInSection.containsKey(section))
		sections.rowsInSection.put(section, 0);

	sections.rowsInSection.put(section, sections.rowsInSection.get(section) + 1);
	//log.info("section" + section + ":" + sections.rowsInSection.get(section));
	
	//log.info(mat[2] + " [" + section + "],\t" + sections);
	
	return section;
}

def getContentAsString(str){

        BufferedReader br = new BufferedReader(new InputStreamReader(str));
        StringBuffer buf = new StringBuffer();
        String line = null;
        while((line = br.readLine()) != null)
                buf.append(line).append("\n");

        return buf.toString();
}


String content = "";
URL url = new URL(uriRoot);

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");

OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
	writer.write("m=pc");
	writer.write("&a=do_o_login");
	writer.write("&login_params=");
	writer.write("&username=ohta_h@agricom.co.jp");
	writer.write("&password=8ma8ru");
	writer.close();

final int MAX_RETRY = 5;
int http_res = -1;
int retryCount = 0;
while(http_res != HttpURLConnection.HTTP_OK){
	try{
		http_res = connection.getResponseCode();
		if (http_res == HttpURLConnection.HTTP_OK) {
		    // OK
			break;
		} else {
		    // Server returned HTTP error code.
		    Thread.sleep(1000);
		}
	}catch(Exception ex){}
	
	retryCount++;
	if(retryCount == MAX_RETRY)
		break;
}

content = getContentAsString(url.openStream());

//response.setContentType("text/javascript+json; charset=utf-8");
response.setContentType("text/html; charset=utf-8");

StringBuffer buf = new StringBuffer();
//Posts
buf.append("{\"posts\":");

def mat = content =~ /<li>[\s\t\n]*<span class=\"date\">[\s\t\n]*([^<\s\t\n]*)[\s\t\n]*<\/span>[\s\t\n]*<a href=\"(\.\/[^\">]*)\">([^<>]*)<\/a>[\s\t\n]*([^<>\s\t\n]*)[\s\t\n]*</
printMatches(mat);
def sections = new TopPageSection();
buf.append(convertMatchesToJson(mat, ["section","date","url","title","auther"], this.&getTopPageSection, sections));

buf.append(",\"rowsInSection\":{");
def secCount = 0;
for(Integer k:sections.rowsInSection.keySet()){
	if(secCount > 0)
		buf.append(",");

	buf.append("\"").append(k).append("\":").append(sections.rowsInSection.get(k));
	secCount++;
}
buf.append("}");

buf.append(",\"communities\":");
mat = content =~ /<a href=\"(\.\/[^>]*a=page_c_home&amp;target_c_commu_id[^>]*)\">([^<>]*)<\/a>/
buf.append(convertMatchesToJson(mat, ["section","url","name"], this.&returnZero, new String()));
buf.append("}");

out.println buf.toString();

